from typing import Generic, TypeVar, Optional, Dict, Any, List

from fastapi.responses import JSONResponse
from pydantic import BaseModel

# 用于泛型类型
T = TypeVar('T')

class ResponseModel(BaseModel, Generic[T]):
    """统一API响应模型"""
    code: int = 0
    errorMsg: str = ""
    data: Optional[T] = None
    total: Optional[int] = None
    
    class Config:
        arbitrary_types_allowed = True

class Response:
    """响应工具类，用于生成统一格式的API响应"""
    
    @staticmethod
    def success(data: Any = None, total: Optional[int] = None) -> Dict[str, Any]:
        """成功响应
        
        Args:
            data: 响应数据
            total: 数据总数，用于分页
            
        Returns:
            Dict: 统一格式的成功响应
        """
        return {
            "code": 0,
            "errorMsg": "",
            "data": data,
            "total": total
        }
    
    @staticmethod
    def error(code: int = 500, error_msg: str = "服务器内部错误") -> Dict[str, Any]:
        """错误响应
        
        Args:
            code: 错误代码
            error_msg: 错误信息
            
        Returns:
            Dict: 统一格式的错误响应
        """
        return {
            "code": code,
            "errorMsg": error_msg,
            "data": None
        }
    
    @staticmethod
    def page_success(data: List[Any], total: int) -> Dict[str, Any]:
        """分页成功响应
        
        Args:
            data: 分页数据列表
            total: 数据总数
            
        Returns:
            Dict: 统一格式的分页成功响应
        """
        return {
            "code": 0,
            "errorMsg": "",
            "data": data,
            "total": total
        }
